<template>
  <view class="container">
    <NavBar title="上传活动台账" />
    <view class="container-item">
      <uni-forms
        ref="baseForm"
        :modelValue="baseFormData"
        labelWidth="100px"
        label-position="left"
      >
        <uni-forms-item label="活动名称" required class="change_style">
          <uni-easyinput
            type="text"
            v-model="baseFormData.activityTheme"
            placeholder="请填写"
          />
        </uni-forms-item>

        <uni-forms-item label="所属支部" required class="change_style">
          <text>{{ baseFormData.djDeptName }}</text>
        </uni-forms-item>

        <uni-forms-item label="活动类型" required>
          <uni-data-select
            v-model="baseFormData.activityType"
            clear
            :localdata="range"
            placeholder="请选择"
          >
          </uni-data-select>
        </uni-forms-item>

        <!-- 活动开始时间只能是小于当前时间，
				结束时间，大于开始时间小于当前是时间 -->

        <uni-forms-item label="开始时间" required>
          <uni-datetime-picker
            type="datetime"
            :clear-icon="false"
            return-type="timestamp"
            :border="false"
            v-model="baseFormData.activityStartTime"
            @click="chuanci"
            @change="changeStart"
            placeholder="请选择"
          />
        </uni-forms-item>

        <uni-forms-item label="结束时间" required>
          <uni-datetime-picker
            type="datetime"
            :clear-icon="false"
            return-type="timestamp"
            v-model="baseFormData.activityEndTime"
            :border="false"
            @click="chuanci"
            @change="changeEnd"
            placeholder="请选择"
          />
        </uni-forms-item>

        <uni-forms-item label="活动地点">
          <uni-easyinput
            type="text"
            v-model="baseFormData.activityPlace"
            placeholder="请填写"
          />
        </uni-forms-item>

        <uni-forms-item
          label="参与人员"
          style="text-align: right; position: relative"
        >
          <text @click="choosePeole">请选择</text>
        </uni-forms-item>

        <view class="people_text" v-show="personnel.length">
          <view v-for="(i, index) in personnel" :key="index">
            {{ i.name }}
          </view>
        </view>

        <uni-forms-item label="活动照片" style="margin-bottom: 0 !important">
        </uni-forms-item>
        <view class="pic_upload" style="display: flex">
          <view
            class="_pic"
            v-for="(i, index) in baseFormData.coverUrl"
            :key="index"
          >
            <image
              class="del_img"
              src="../../static/dangjian/del_img.png"
              style="width: 40rpx; height: 40rpx"
              @click="delUploadImg(index)"
            ></image>
            <image :src="i" style="width: 210rpx; height: 210rpx"></image>
          </view>
          <uni-file-picker
            file-extname="png,jpg"
            :del-icon="false"
            mode="list"
            :limit="9"
            @select="selectPic"
            @progress="picProgress"
            @success="successPic"
            @fail="failPic"
            @delete="deletePic"
          >
            <view class="upload_img">
              <i
                class="iconfont icon-xiangji1fill"
                style="color: #3b95ff; font-size: 52rpx"
              ></i>
              <view>上传照片</view>
            </view>
          </uni-file-picker>
        </view>

        <view class="upload_file">
          <uni-forms-item label="附件" required> </uni-forms-item>
          <lsj-upload
            ref="lsjUpload"
            childId="upload1"
            style="width: 20%; text-align: right"
            :size="uploadconfig2.size"
            :instantly="uploadconfig2.instantly"
            :formats="uploadconfig2.formats"
            :option="option"
            @change="onChange"
            @uploadEnd="onuploadEnd"
            @fail="failFile"
            @progress="onProgress"
          >
            <view
              style="width: 100%; text-align: right; color: #3c95ff"
              @click="fuckyou"
            >
              <i
                class="iconfont icon-24gf-folderOpen"
                style="color: #3c95ff"
              ></i>
              上传
            </view>
          </lsj-upload>
        </view>
        <progress v-if="percent !=0&&percent !=100" :percent="percent" show-info stroke-width="3" />
        <view v-if="baseFormData.accessoryUrl.length">
          <view
            class="file_list"
            v-for="(item, index) in baseFormData.accessoryUrl"
            :key="index"
          >
            <view class="file_list_item">
              <view @click="prveFileBtn(item)">{{ item.accessoryName }}</view>
            </view>
            <view
              class="iconfont icon-close"
              style="color: #e86565; font-size:24rpx"
              @click="delFile(index)"
            ></view>
          </view>
        </view>

        <view style="padding-top: 20px"></view>
        <view class="btns">
          <button
            class="save-draft"
            style="background: #d3d3d3"
            @click="resetUp"
          >
            取消
          </button>
          <button
            class="publish"
            style="background: #3b95ff"
            :disabled="disabledPublish"
            :loading="publishLoading"
            @click="uploadBtn"
          >
            确定
          </button>
        </view>
        <view style="padding-top: 20px"></view>
      </uni-forms>
    </view>
  </view>
</template>

<script>
// 接口
import {
  getJoinUser,
  apiUploadTaiZhang, // 上传活动台账
  // apiChamberList,
} from "../../net/dagnqunhuodong.js";

import { previewPic, timestampToTime } from "../../utils/fun.js";
import { uploadconfig2 } from "../../const";
import {
  prevFile, // 预览文件
} from "../../utils/preview.js";

import NavBar from "@/components/NavBar.vue";
export default {
  components: {
    NavBar,
  },
  data() {
    return {
      uploadconfig2,
      option: {
        url: uploadconfig2.url,
        name: "file",
        header: {
          Authorization: uni.getStorageSync("token"), platform: 'APP'
        },
        formData: {},
      },
      percent:0,

      inputActivityPlace: "",
      start: "",
      end: "",
      isTaiZhang: false, // true 从台账列表跳转，创建台账
      uploadURL: "/masses/common/upload", // 上传接口地址
      formPage: "", // 来自哪个页面
      // 比较开始时间和结束时间
      StartTime: 0,
      EndTime: 0,
      visible: false,
      choosePeoName: [],
      range2: [], //活动地点
      isFlag: true,
      disabledDraft: false,
      draftLoading: false,
      disabledPublish: false,
      publishLoading: false,
      tabIndex: 0,
      // 文件回显列表
      files: new Map(),
      // 参与人员
      personnelArr: [],
      personnel: [],
      // 活动类型
      range: [],
      typeClassArr: [],
      suffix: "", //后缀名
      baseFormData: {
        activityType: "",
        activityStartTime: "",
        activityEndTime: "",
        participant: [],
        coverUrl: [],
        accessoryUrl: [],
        activityPlace: "",
        djDeptName: "",
      },
    };
  },

  onShow() {
    let djDeptId = JSON.parse(uni.getStorageSync("loginUserInfo")).djDeptId;
    this._getJoinUser(djDeptId); // 获取选择的参与人员
    if (uni.getStorageSync("participant")) {
      this.personnel = JSON.parse(uni.getStorageSync("participant"));
    } else {
      this.personnel = [];
    }
    this.start = timestampToTime();
    // 活动类型
    this.range = JSON.parse(uni.getStorageSync("typeClassArr")).map((v) => {
      return {
        value: v.enumId,
        text: v.name,
      };
    });

    // 活动地点
    // let placeArr = JSON.parse(uni.getStorageSync("activityPlaceArr"));
    // let idx = 0;
    // for (let i = 0; i < placeArr.lemgth; i++) {
    //   idx++;
    //   this.range2.push({
    //     index: idx,
    //     value: placeArr[i].value,
    //     text: placeArr[i].text,
    //   });
    // }

    // this.range2.push({
    //   index: this.range2.legnth,
    //   value: 6,
    //   text: "其他",
    // });

    // this.getApiChamberList();

    this.baseFormData.djDeptName = JSON.parse(
      uni.getStorageSync("loginUserInfo")
    ).djDeptName;
    setTimeout(() => {
      this.fuckyou();
    }, 1000);
  },
  onLoad() {},
  methods: {
    uniShowToast(title, icon = "error") {
      uni.showToast({
        title,
        icon,
        mask: true,
      });
    },

        // 穿刺一击让他们的遮罩层消失
    chuanci() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
    },
    // 穿刺一击让他们的遮罩层消失
    chuanci2() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
    },

    resetUp() {
      this.personnelArr = [];
      this.personnel = [];
      uni.removeStorage({
        key: "participant",
      });
      this.baseFormData = {
        activityType: "",
        activityStartTime: "",
        activityEndTime: "",
        participant: [],
        coverUrl: [],
        accessoryUrl: [],
        activityPlace: "",
        djDeptName: JSON.parse(uni.getStorageSync("loginUserInfo")).djDeptName,
      };
    },

    // 跳转页面,选择参与人员
    choosePeole() {
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
      this.$forceUpdate();
      uni.navigateTo({
        url: `../../pages/DJinitiateActivities/choosePeople?personnelArr=${JSON.stringify(
          this.personnelArr
        )}`,
      });
    },
    onProgress(res){
     this.percent = res.progress; 
    },

    // 上传附件失败
    failFile() {
      uni.showToast({
	      title: '上传失败',
        icon: 'error',
        mask: true,
	      duration: 1500
      });
    },

    prveFileBtn(item) {
      prevFile(item);
    },

    // 删除图片
    delUploadImg(index) {
      this.baseFormData.coverUrl.splice(index, 1);
    },

    // 上传
    uploadBtn() {
      console.log(this.baseFormData.activityType, this.inputActivityPlace);
      console.log(this.baseFormData);
      // 判断活动地点是否为输入的
      // if (this.baseFormData.activityPlace == 6) {
      //   this.baseFormData.activityPlace = this.inputActivityPlace;
      //   this.baseFormData.activityType = 6;
      // }

      if (!this.baseFormData.activityTheme) {
        this.uniShowToast("请填写活动名称");
        return;
      } else if (this.baseFormData.activityType == "") {
        this.uniShowToast("请选择活动类型");
        return;
      } else if(!this.baseFormData.activityStartTime) {
        this.uniShowToast("请选择开始时间");
        return;
      } else if(!this.baseFormData.activityEndTime) {
        this.uniShowToast("请选择结束时间");
        return;
      } else if (!this.baseFormData.accessoryUrl.length) {
        this.uniShowToast("请选择附件");
        return;
      }

      // 活动人员
      let participantArr = this.personnel;

      let data = {
        participant: JSON.stringify(participantArr),
        activityTheme: this.baseFormData.activityTheme,
        djDeptName: this.baseFormData.djDeptName,
        activityType: this.baseFormData.activityType,
        activityStartTime: this.baseFormData.activityStartTime,
        activityEndTime: this.baseFormData.activityEndTime,
        coverUrl: JSON.stringify(this.baseFormData.coverUrl),
        accessoryUrl: JSON.stringify(this.baseFormData.accessoryUrl),
        activityPlace: this.baseFormData.activityPlace,
        djDeptId: JSON.parse(uni.getStorageSync("loginUserInfo")).djDeptId,
        userId: JSON.parse(uni.getStorageSync("loginUserInfo")).uid,
      };
      console.log(data);

      apiUploadTaiZhang(data)
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            this.resetUp();
            // this._getJoinUser(); // 获取选择的参与人员
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 选择参与人员
    changePeo(item, index) {
      if (item.flag) {
        item.flag = false;
      } else {
        item.flag = true;
      }
    },

    // 删除图片地址
    delPicUrl() {
      this.baseFormData.coverUrl = [];
    },

    // 预览 图片
    prePic(url) {
      let arr = [url];
      previewPic(arr);
    },

    // 判断开始时间和结束时间
    changeStart(e) {
      console.log(e,'显示');
      this.StartTime = e;
    },
    changeEnd(e) {
      this.EndTime = e;
    },

    bindPickerChange(e) {
      this.visible = !this.visible;
      let index = e.detail.value;
    },

    // 删除附件
    delFile() {
      for (let i = 0; i < this.baseFormData.accessoryUrl.length; i++) {
        this.baseFormData.accessoryUrl.splice(i, 1);
      }
      this.fuckyou();
    },

    // // 获取活动地点
    // getApiChamberList() {
    // 	apiChamberList()
    // 		.then((res) => {
    // 			console.log(res);
    // 			this.range2 = res.data.map((v) => {
    // 				return {
    // 					value: v.id,
    // 					text: v.name,
    // 				};`
    // 			});

    // 			uni.setStorage({
    // 				key: "activityPlaceArr",
    // 				data: JSON.stringify(this.range2),
    // 			});
    // 		})
    // 		.catch((err) => {
    // 			console.log(err);
    // 			this.range2 = [];
    // 		});
    // },

    // 获取参与人员
    _getJoinUser(djDeptId) {
      getJoinUser(djDeptId)
        .then((res) => {
          this.personnelArr = res.data.map((v) => {
            return {
              value: v.id,
              text: v.name,
              phone: v.phone,
              flag: false,
            };
          });
        })
        .catch((err) => {});
    },
    fuckyou() {
      this.$forceUpdate();
      this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
      this.$refs.lsjUpload && this.$refs.lsjUpload.show();
    },

    // 上传附件的操作
    // 选择文件后触发
    selectPic(file) {
      let that = this;
      for (let i = 0; i < file.tempFilePaths.length; i++) {
        uni.uploadFile({
          url: uploadconfig2.url,
          filePath: file.tempFilePaths[i],
          name: "file",
          header: {
            Authorization: uni.getStorageSync("token"), platform: 'APP'
          },
          success(res) {
            let data = JSON.parse(res.data);
            console.log(data);
            that.baseFormData.coverUrl.push(data.data.url);
          },
          file(err) {
            console.log(err);
          },
        });
      }
    },
    // 文件上传时触发
    picProgress(item) {
      if (item.progress != 100) {
        uni.showLoading({
          title: "上传中……",
          mask: true,
        });
      } else {
        uni.hideLoading();
      }
    },
    // 上传成功触发
    successPic(file) {
      console.log(file);
    },
    // 上传失败触发
    failPic(file) {
      console.log(file);
      uni.hideLoading();
    },
    // 文件从列表移除时触发
    deletePic(file) {
      console.log(file);
    },

    // 上传文件的操作
    // 选择文件触发，返回所有已选择文件Map集合
    onChange(files) {
      this.files = files;
      this.$forceUpdate();
    },

    // 上传结束回调，返回参数与progress一致
    onuploadEnd(item) {
      let res = JSON.parse(item.responseText);
      if (res.code === 0) {
        this.baseFormData.accessoryUrl.push({
          accessoryUrl: JSON.parse(item.responseText).data.url,
          accessoryName: item.name,
        });
        this.suffix = item.name.substring(item.name.lastIndexOf(".") + 1);
      }

      // 更新当前窗口状态变化的文件
      this.files.set(item.name, item);
      // 强制更新视图
      this.$forceUpdate();
    },

    clickRightFn() {
      uni.navigateTo({
        url: "../DJinitiateActivitiesList/index",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "/static/dangjian.scss";
page {
  background: #fff;
}

.change_style {
  display: flex;
  align-items: center;
  text-align: right;
}

/* 上传文件 */
.upload_file {
  margin-top: 40rpx;
  display: flex;
  height: 80rpx;
  justify-content: space-between;
}

::v-deep .uni-popper__arrow {
  left: 80% !important;
}

/* 参与人员 1 */
.people_text {
  width: 700rpx;
  min-height: 100rpx;
  padding: 8rpx;
  box-sizing: border-box;
  background: #f3f5f8;
  border-radius: 8rpx;
  border: 1rpx solid #d6dbe3;
  font-size: 30rpx;
  color: #0e1634;
  display: flex;
  flex-wrap: wrap;
}

.people_text view {
  margin-right: 16rpx;
  color: #999;
  min-width: 90rpx;
}

::v-deep .uni-checkbox-input {
  border-radius: 50%;
  width: 32rpx;
  height: 32rpx;
}

/* 参与人员 2 */

.form_item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.container{
  background: #fff;
  height: 100%;
}

.container-item {
  width: 700rpx;
  margin: 0 auto;
}

.btns {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 auto;
}

.btns button {
  width: 340rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 10rpx;
  text-align: center;
  color: #fff;
  font-size: 26rpx;
}

.save-draft {
  background: #f8b86d;
}

.publish {
  background: #3c95ff;
}

/* 预览图片 */
.cover_pic {
  width: 200rpx;
  height: 132rpx;
  position: absolute;
  right: 0;
}

.cover_pic i {
  color: red;
  font-size: 36rpx;
  position: absolute;
  z-index: 100;
  right: 0;
  top: 0;
}

/* 参与人员 */
.join_peo {
  position: absolute;
  right: 0;
  width: 150rpx;
  height: 70rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10rpx;
  box-sizing: border-box;
  font-size: 24rpx;
  color: #6a6a6a;
}

.picker_views {
  position: absolute;
  z-index: 100;
  top: 100rpx;
  width: 100%;
  height: 350rpx;
  background: #fff;
  border-radius: 8rpx;
  border: 2rpx solid #e5e5e5;
  text-align: center;
}

.upload_img {
  padding-top: 60rpx;
  box-sizing: border-box;
  width: 210rpx;
  height: 210rpx;
  background-color: rgba(214, 219, 227, 0.6);
  color: #3b95ff;
  text-align: center;
}

.upload_img i {
  display: inline-block;
}

/* 活动内容 */
.textarea_con {
  margin-bottom: 20rpx;
  width: 700rpx;
  min-height: 220rpx;
  position: relative;
}

.text_num {
  position: absolute;
  right: 8rpx;
  bottom: 10rpx;
  font-size: 30rpx;
  color: #999999;
}

.textarea_text {
  margin: 0 auto;
  width: 700rpx;
  min-height: 220rpx;
  background: #f3f5f8 !important;
  border-radius: 8rpx;
  border: 1rpx solid #d6dbe3;
  padding: 20rpx;
  box-sizing: border-box;
}

.textarea_plac {
  font-size: 30rpx;
  font-weight: 500;
  color: #0e1634;
}

/* 重置样式 */
::v-deep .is-input-border,
::v-deep .uni-select,
::v-deep .uni-date-x--border {
  text-align: right;
  border: none !important;
}

::v-deep .uni-date {
  position: absolute;
  right: 0;
  /* 		width: 400rpx; */
}

::v-deep .icon-xiangxia1:before {
  content: "&#xe603;" !important;
}

::v-deep .uniui-calendar {
  position: absolute;
  right: 0;
}

::v-deep .uni-date-editor--x {
  text-align: right !important;
  padding-right: 5rpx;
}

::v-deep .uni-forms-item {
  margin-bottom: 10rpx;
}

/* 封面上传控件 */
.pic_upload {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pic_upload ._pic {
  margin-right: 20rpx;
  position: relative;
}

.pic_upload ._pic .del_img {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  z-index: 100;
}

.pic_upload ._pic image {
  border-radius: 8rpx;
}

::v-deep .file-picker__box {
  /* 		position: absolute !important;
		right: 0 !important; */
  width: 210rpx !important;
  height: 210rpx !important;
  margin-right: 30rpx !important;
}

::v-deep .file-picker__box-content {
  border: none !important;
}

::v-deep .file-image,
::v-deep .file-picker__box-content {
  width: 210rpx !important;
  height: 210rpx !important;
  border-radius: 8rpx !important;
  overflow: hidden !important;
}


::v-deep .is-text-box {
  display: none;
}

/* 封面上传控件 */

/* ::v-deep .uni-input-placeholder,
::v-deep .uni-select__input-text,
::v-deep .uni-select__input-placeholder,
.join_peo text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  color: #0e1634 !important;
} */

::v-deep .uni-forms-item__label {
  font-size: 32rpx !important;
  color: #000 !important;
}
/* uni-forms-item__content 参与人员 */
::v-deep .uni-forms-item__content,
::v-deep .uni-select__input-text,
::v-deep .uni-textarea-textarea,
::v-deep .uni-input-input{
  color: #999 !important;
  font-size: 28rpx !important;
}
</style>
